<?php

namespace Ignus\View;

class TokenParserBroker implements TokenParserBrokerInterface
{
    protected $parser;

    /**
     * @var \Ignus\View\TokenParserInterface[]
     */
    protected $parsers = array();

    /**
     * @var \Ignus\View\TokenParserBrokerInterface[]
     */
    protected $brokers = array();

    /**
     * @param \Ignus\View\TokenParserInterface[] $parsers
     * @param \Ignus\View\TokenParserBrokerInterface[] $brokers
     * @throws \Ignus\View\Error
     */
    public function __construct($parsers = array(), $brokers = array())
    {
        foreach ($parsers as $parser)
            $this->parsers[$parser->getTag()] = $parser;

        foreach ($brokers as $broker)
            $this->brokers[] = $broker;
    }

    public function addTokenParser(TokenParserInterface $parser)
    {
        $this->parsers[$parser->getTag()] = $parser;
    }

    public function addTokenParserBroker(TokenParserBroker $broker)
    {
        $this->brokers[] = $broker;
    }

    /**
     * @return \Ignus\View\TokenParserInterface
     */
    public function getTokenParser($tag)
    {
        if (isset($this->parsers[$tag])) {
            return $this->parsers[$tag];
        }
        $broker = end($this->brokers);
        while (false !== $broker) {
            $parser = $broker->getTokenParser($tag);
            if (null !== $parser) {
                return $parser;
            }
            $broker = prev($this->brokers);
        }
        return null;
    }

    public function getParser()
    {
        return $this->parser;
    }

    public function setParser(ParserInterface $parser)
    {
        $this->parser = $parser;
        foreach ($this->parsers as $tokenParser) {
            $tokenParser->setParser($parser);
        }
        foreach ($this->brokers as $broker) {
            $broker->setParser($parser);
        }
    }
}
